package com.chat.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: WFP
 * @Time: 2017/12/30
 * @decription:
 */
public class ChatListener implements ServletContextListener , HttpSessionAttributeListener,HttpSessionListener {
    // 声明一个ServletContext对象
    private ServletContext application = null ;

    @Override
    public void contextInitialized(ServletContextEvent sce)
    {
        // 容器初始化时，向application中存放一个空的容器
        this.application = sce.getServletContext() ;
        this.application.setAttribute("alluser",new ArrayList()) ;
        this.application.setAttribute("allmap",new HashMap<String,HttpSession>());
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        {
            // 将用户名称从列表中删除
            List<String> l = (List<String>) this.application.getAttribute("alluser");
            String value = (String) httpSessionEvent.getSession().getAttribute("uname");
            l.remove(value);
            this.application.setAttribute("alluser", l);

            //将该用户对应的"用户名--->HttpSession"键值对从map中删除
            Map<String, HttpSession> m = (Map<String, HttpSession>) this.application.getAttribute("allmap");
            m.remove(httpSessionEvent.getSession());
            this.application.setAttribute("allmap", m);
        }
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        //判断用户是否是第一次登录
        if(httpSessionBindingEvent.getSession().getAttribute("message")==null) {
            // 如果登陆成功，则将用户名保存在列表之中
            List l = (List) this.application.getAttribute("alluser");
            l.add(httpSessionBindingEvent.getValue());
            this.application.setAttribute("alluser", l);

            //如果登陆成功，则将"用户名--->HttpSession"这样的键值对保存在map中
            Map<String, HttpSession> m = (Map<String, HttpSession>) this.application.getAttribute("allmap");
            m.put((String) httpSessionBindingEvent.getValue(), httpSessionBindingEvent.getSession());
            this.application.setAttribute("allmap", m);
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }
}
